<template>
  <div class="loading-page">
    <div v-if="!user.username && !user.userId" class="loading-animation">
      <div class="spinner">
        <div class="rect rect1" />
        <div class="rect rect2" />
        <div class="rect rect3" />
        <div class="rect rect4" />
        <div class="rect rect5" />
      </div>
      <div class="loading-text">加载中...</div>
    </div>
    <auth-info v-else-if="!user.username" :data="user" @change="toHome" />
  </div>
</template>

<script>
import { login, getUser } from "@/api";
import Taro from "@tarojs/taro";
import { mapGetters } from "vuex";
import AuthInfo from "./components/AuthInfo.vue";

export default {
  components: {
    AuthInfo: AuthInfo
  },
  data() {
    return {
      user: {}
    };
  },
  computed: mapGetters(["token"]),
  onLoad() {
    this.login();
  },
  methods: {
    async login() {
      const { code } = await Taro.login();
      if (code) {
        const { token } = await login(code);
        this.$store.commit("setToken", token);
        this.getUserInfo();
      }
    },
    async getUserInfo() {
      this.user = await getUser();
      if (this.user.username) {
        this.toHome(this.user);
      }
    },
    toHome(user) {
      this.$store.commit("setUser", user);
      Taro.reLaunch({
        url: "/pages/home/index"
      });
    }
  }
};
</script>

<style lang="less">
@import "./index.less";
</style>
